package com.it.schoolbookshop_back.service.impl;

import com.it.schoolbookshop_back.entities.po.Rating;
import com.it.schoolbookshop_back.entities.po.Transaction;
import com.it.schoolbookshop_back.mapper.RatingMapper;
import com.it.schoolbookshop_back.mapper.TransactionMapper;
import com.it.schoolbookshop_back.service.RatingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 评分服务实现类
 */
@Slf4j
@Service
public class RatingServiceImpl implements RatingService {
    
    @Autowired
    private RatingMapper ratingMapper;
    
    @Autowired
    private TransactionMapper transactionMapper;
    
    @Override
    public boolean createRating(Rating rating) {
        try {
            // 检查交易是否存在且已完成
            Transaction transaction = transactionMapper.selectById(rating.getTransactionId());
            if (transaction == null) {
                log.warn("交易{}不存在", rating.getTransactionId());
                return false;
            }
            
            if (!"completed".equals(transaction.getStatus())) {
                log.warn("交易{}未完成，不能评价", rating.getTransactionId());
                return false;
            }
            
            // 检查评分人是否是交易的买方
            if (!rating.getRaterId().equals(transaction.getBuyerId())) {
                log.warn("用户{}不是交易{}的买方，不能评价", 
                    rating.getRaterId(), rating.getTransactionId());
                return false;
            }
            
            // 设置被评分人为交易的卖方
            rating.setRatedId(transaction.getSellerId());
            
            // 检查是否已经评价过
            Rating existingRating = ratingMapper.selectByTransactionAndRater(
                rating.getTransactionId(), rating.getRaterId());
            if (existingRating != null) {
                log.warn("用户{}已经对交易{}评价过", rating.getRaterId(), rating.getTransactionId());
                return false;
            }
            
            // 插入评分记录
            int result = ratingMapper.insert(rating);
            if (result > 0) {
                log.info("用户{}对交易{}评价成功，被评分人：{}", 
                    rating.getRaterId(), rating.getTransactionId(), rating.getRatedId());
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("创建评分失败", e);
            return false;
        }
    }
    
    @Override
    public Rating getRatingByTransactionAndRater(Integer transactionId, Integer raterId) {
        return ratingMapper.selectByTransactionAndRater(transactionId, raterId);
    }
    
    @Override
    public List<Rating> getRatingsByUserId(Integer userId) {
        return ratingMapper.selectByUserId(userId);
    }

    @Override
    public List<Rating> getRatingsByRatedId(Integer ratedId) {
        return ratingMapper.selectByRatedId(ratedId);
    }
} 